#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
数据处理API服务器启动脚本
作者: jena 

"""

import os
import sys
import argparse
import subprocess
from pathlib import Path

# 添加项目根目录到Python路径，确保正确的模块导入
script_dir = Path(__file__).parent
project_root = script_dir.parent
if str(project_root) not in sys.path:
    sys.path.insert(0, str(project_root))

# 设置离线包路径 - 使用统一的路径设置函数
from src.common_utils import setup_offline_packages_path
setup_offline_packages_path(__file__)


def check_dependencies():
    """检查依赖是否安装 - 仅支持 FastAPI + Uvicorn"""
    try:
        # 仅检查 FastAPI 服务器模块
        fastapi_available = False
        try:
            from src import api_server_fastapi  # noqa: F401
            print("✅ FastAPI 服务器模块导入成功")
            fastapi_available = True
        except ImportError as e:
            print(f"❌ FastAPI 服务器模块导入失败: {e}")
        
        # 检查依赖状态
        missing_deps = []
        try:
            from src.common_utils import check_offline_dependencies, FastAPIDependencyManager
            dep_status = check_offline_dependencies()
            print("📋 依赖状态检查:")
            for dep, info in dep_status.items():
                status = "✅" if info['available'] else "⚠️"
                desc = info['description']
                print(f"   {status} {dep}: {desc}")

            # FastAPI与Uvicorn必须
            fastapi_deps = FastAPIDependencyManager()
            if not fastapi_deps.has_fastapi():
                missing_deps.append("fastapi")
            if not fastapi_deps.has_uvicorn():
                missing_deps.append("uvicorn")
        except Exception as e:
            print(f"⚠️ 依赖状态检查失败: {e}")
        
        if missing_deps or not fastapi_available:
            print(f"❌ 缺少关键依赖: {', '.join(missing_deps)}")
            print("\n📦 推荐使用离线安装脚本 (最佳选择):")
            print("   python install_offline_packages.py")
            print("\n🌐 或者使用在线安装:")
            print("   pip install -r requirements.txt")
            return False
        
        print("✅ 依赖检查通过")
        return True
    except Exception as e:
        print(f"❌ 依赖检查过程出错: {e}")
        return False


def start_server(host='127.0.0.1', port=5000, debug=False):
    """启动API服务器 - 仅FastAPI(uvicorn)"""
    if not check_dependencies():
        return False

    project_root = Path(__file__).parent.parent
    os.chdir(project_root)

    print(f"🚀 启动数据处理API服务器...")
    print(f"📍 地址: http://{host}:{port}")
    print(f"🔧 调试模式: {'开启' if debug else '关闭'}")
    print("按 Ctrl+C 停止服务器")
    print("-" * 50)

    try:
        # 启动 FastAPI + Uvicorn
        from src.api_server_fastapi import app as fastapi_app
        from src.common_utils import FastAPIDependencyManager
        fastapi_deps = FastAPIDependencyManager()
        uvicorn = fastapi_deps.get_uvicorn()
        if uvicorn is not None:
            print("🔄 正在启动 FastAPI (Uvicorn ASGI) 应用...")
            uvicorn.run(fastapi_app, host=host, port=port, reload=False)
            return True
        else:
            raise RuntimeError("Uvicorn不可用，无法以ASGI模式启动")

    except KeyboardInterrupt:
        print("\n👋 服务器已停止")
    except OSError as e:
        if "Address already in use" in str(e) or "WinError 10048" in str(e):
            print(f"❌ 端口 {port} 已被占用，请尝试其他端口")
            print(f"   例如: python start_api.py --port {port + 1}")
        else:
            print(f"❌ 网络错误: {e}")
        return False
    except Exception as e:
        print(f"❌ 启动失败: {e}")
        print("请检查错误信息并确保FastAPI与Uvicorn已正确安装到offline_packages")
        return False

    return True


def main():
    """主函数"""
    parser = argparse.ArgumentParser(
        description="数据处理API服务器启动脚本",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
使用示例:
  python start_api.py                    # 默认启动 (127.0.0.1:5000)
  python start_api.py --host 0.0.0.0    # 允许外部访问
  python start_api.py --port 8080       # 指定端口
  python start_api.py --debug            # 开启调试模式
  python start_api.py --check            # 仅检查依赖
        """
    )
    
    parser.add_argument(
        '--host', 
        default='127.0.0.1',
        help='服务器地址 (默认: 127.0.0.1)'
    )
    
    parser.add_argument(
        '--port', 
        type=int, 
        default=5000,
        help='服务器端口 (默认: 5000)'
    )
    
    parser.add_argument(
        '--debug', 
        action='store_true',
        help='开启调试模式'
    )
    
    parser.add_argument(
        '--check', 
        action='store_true',
        help='仅检查依赖，不启动服务器'
    )
    
    args = parser.parse_args()
    
    if args.check:
        success = check_dependencies()
        sys.exit(0 if success else 1)
    
    success = start_server(args.host, args.port, args.debug)
    sys.exit(0 if success else 1)


if __name__ == "__main__":
    main()